package com.bigdata.booklibraryseatapi.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bigdata.booklibraryseatapi.common.exception.BusinessException;
import com.bigdata.booklibraryseatapi.common.exception.ResponseCode;
import com.bigdata.booklibraryseatapi.common.pojo.PageResult;
import com.bigdata.booklibraryseatapi.entity.Area;
import com.bigdata.booklibraryseatapi.mapper.AreaMapper;
import com.bigdata.booklibraryseatapi.service.IAreaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bigdata.booklibraryseatapi.vo.req.AddAreaReqVO;
import com.bigdata.booklibraryseatapi.vo.req.EditAreaReqVO;
import com.bigdata.booklibraryseatapi.vo.req.PageAreaReqVO;
import com.bigdata.booklibraryseatapi.vo.resp.AreaListRespVO;
import com.bigdata.booklibraryseatapi.vo.resp.PageAreaRespVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 区 服务实现类
 * </p>
 *
 * @author book
 * @since 2023-12-13
 */
@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements IAreaService {

    @Resource
    private AreaMapper areaMapper;

    @Override
    public void addArea(AddAreaReqVO vo) {
        Area area = query().select("id").last("limit 1").eq("label", vo.getLabel()).one();
        if (area != null) {
            throw new BusinessException(ResponseCode.ACCOUNT_ALREADY_EXISTS.getCode(), ResponseCode.ACCOUNT_ALREADY_EXISTS.getMessage());
        }
        Area insertArea = new Area();
        BeanUtils.copyProperties(vo,insertArea);
        insertArea.setStatus(1);
        int result = areaMapper.insert(insertArea);
        if(result!=1){
            throw new BusinessException(ResponseCode.OPERATION_ERROR.getCode(), ResponseCode.OPERATION_ERROR.getMessage());
        }
    }

    @Override
    public void editArea(EditAreaReqVO vo) {
        Area area = areaMapper.selectById(vo.getId());
        if (area == null) {
            throw new BusinessException(ResponseCode.ACCOUNT_ALREADY_EXISTS.getCode(), ResponseCode.ACCOUNT_ALREADY_EXISTS.getMessage());
        }
        BeanUtils.copyProperties(vo,area);
        int result = areaMapper.updateById(area);
        if(result!=1){
            throw new BusinessException(ResponseCode.OPERATION_ERROR.getCode(), ResponseCode.OPERATION_ERROR.getMessage());
        }
    }

    @Override
    public List<AreaListRespVO> getAreaList() {
        return areaMapper.getAreaList();
    }

    @Override
    public PageResult<PageAreaRespVO> pageArea(PageAreaReqVO vo) {
        IPage<PageAreaRespVO> result = areaMapper.selectPageArea(new Page<>(vo.getCurrent(), vo.getSize()), vo);
        return PageResult.getPage(result.getRecords(), result.getTotal());
    }
}
